package com.fmx.BookStore.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fmx.BookStore.core.domain.AjaxResult;
import com.fmx.BookStore.domain.Permission;
import com.fmx.BookStore.domain.RolePermission;
import com.fmx.BookStore.domain.User;
import com.fmx.BookStore.mapper.RolePermissionMapper;
import com.fmx.BookStore.service.IPermissionService;
import com.fmx.BookStore.utils.TokenUtils;
import com.fmx.BookStore.vo.UserRequest;
import com.fmx.BookStore.mapper.UserMapper;
import com.fmx.BookStore.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User>implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Resource
    private IPermissionService permissionService;
    @Resource
    private RolePermissionMapper rolePermissionMapper;
    private static final Log LOG = Log.get();
    @Override
    public User selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    @Override
    public List<User> listUser(User user) {
        return userMapper.listUser(user);
    }

    @Override
    public int insertUser(User user) {
        return userMapper.insertUser(user);
    }

    @Override
    public int updateUser(User user) {
        return userMapper.updateUser(user);
    }

    @Override
    public int deleteUser(Long userId) {
        return userMapper.deleteUser(userId);
    }
    @Override
    public UserRequest login(UserRequest userRequest){
        String username = userRequest.getUserName();
        String password = userRequest.getPassword();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",username);
        queryWrapper.eq("password",password);
        try {
            User user = getOne(queryWrapper);
            if (user != null){
                BeanUtil.copyProperties(user,userRequest,true);
                //设置token
                String token = TokenUtils.genToken(user.getUserId().toString(),user.getPassword());
                userRequest.setToken(token);

                // 设置用户的菜单列表
                List<Permission> roleMenus = getRoleMenus(user.getRoleId());
                userRequest.setPermissionList(roleMenus);
            }
        }catch (Exception e){
            LOG.error(e);
        }
        return userRequest;
    }

    @Override
    public int register(UserRequest userRequest) {
        User user = null;
        int row = 0;
        String username = userRequest.getUserName();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",username);
        try {
            user = getOne(queryWrapper);

        }catch (Exception e){
            LOG.error(e);
        }
        if (user == null){
            user = new User();
            BeanUtil.copyProperties(userRequest,user,true);
            row = insertUser(user);
        }
        return row;
    }

    /**
     * 获取当前角色的菜单列表
     * @param roleId
     * @return
     */
    private List<Permission> getRoleMenus(Long roleId) {
        // 当前角色的所有菜单id集合
        List<Long> menuIds = rolePermissionMapper.selectByRoleId(roleId);

        // 查出系统所有的菜单(树形)
        List<Permission> permissionList = permissionService.findMenus("");
        // new一个最后筛选完成之后的list
        List<Permission> roleMenus = new ArrayList<>();
        // 筛选当前用户角色的菜单
        for (Permission permission : permissionList) {
            if (menuIds.contains(permission.getPermissionId())) {
                roleMenus.add(permission);
            }
            List<Permission> children = permission.getChildren();
            // removeIf()  移除 children 里面不在 menuIds集合中的 元素
            children.removeIf(child -> !menuIds.contains(child.getPermissionId()));
        }
        return roleMenus;
    }


}
